<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="模板名称" prop="templateName">
        <el-input v-model="queryParams.templateName" placeholder="请输入模板名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['commodity:template:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['commodity:template:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['commodity:template:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['commodity:template:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="templateList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="质检模板" align="center" prop="templateName" />
      <!-- 修改后的图片列 -->
      <el-table-column label="图片" prop="templateImagePaths" align="center">
        <template slot-scope="scope">
          <div class="image-container">
            <image-preview v-for="(image, index) in scope.row.templateImagePaths" :key="index" :src="image" :width="50"
              :height="50" class="image-item" />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="质检项" align="center">
        <template slot-scope="scope">
          <span>
            {{ scope.row.customQualityCheck.map(item => item.checkItem).join('、') }}
          </span>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['commodity:template:edit']">编辑</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['commodity:template:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改质检模板对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="模板名称" prop="templateName">
          <el-input v-model="form.templateName" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="质检项">
          <el-table :data="form.customQualityCheck" class="full-width-table" border>
            <el-table-column label="质检项（最多30项）" prop="checkItem" min-width="200">
              <template #default="{ row, $index }">
                <el-form-item :prop="`customQualityCheck.${$index}.checkItem`">
                  <el-input v-model="row.checkItem" placeholder="质检项" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="质检内容" prop="checkContent" min-width="400">
              <template #default="{ row, $index }">
                <el-form-item :prop="`customQualityCheck.${$index}.checkContent`">
                  <el-input type="textarea" v-model="row.checkContent" placeholder="质检内容" :rows="1"
                    :autosize="{ minRows: 1, maxRows: 4 }" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" align="center">
              <template #default="{ $index }">
                <el-button type="text" @click="removeQualityCheckItem($index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button type="primary" icon="el-icon-plus" @click="addQualityCheckItem"
            :disabled="form.customQualityCheck.length >= 30" style="margin-top: 10px;">
            添加质检项
          </el-button>
        </el-form-item>
        <el-form-item label="图片" prop="templateImagePaths">
          <image-upload ref="imageUploadComponent" :auto-upload="autoUpload" v-model="form.templateImagePaths" />
        </el-form-item>
      </el-form>
      <template slot="footer">
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { listTemplate, getTemplate, delTemplate, addTemplate, updateTemplate } from "@/api/commodity/template";
import ImagePreview from "@/components/ImagePreview";
export default {
  components: {
    ImagePreview,
  },
  name: "Template",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 质检模板表格数据
      templateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        templateName: null,
      },
      // 表单参数
      form: {
        templateName: '',
        customQualityCheck: [],
        templateImagePaths: [],
      },
      autoUpload: false,  // 上传图片默认值为false，可以根据需要设置为true
    };
  },
  computed: {
    rules() {
      let rules = {
        templateName: [
          { required: true, message: "模板名称不能为空", trigger: "blur" }
        ],
        // 如果允许图片数量为零，移除 min: 1 的限制
        templateImagePaths: [
          { type: 'array', message: '图片格式不正确', trigger: 'change' }
        ],
      };
      this.form.customQualityCheck.forEach((item, index) => {
        rules[`customQualityCheck.${index}.checkItem`] = [
          { required: true, message: '质检项不能为空', trigger: 'blur' }
        ];
        rules[`customQualityCheck.${index}.checkContent`] = [
          { required: true, message: '质检内容不能为空', trigger: 'blur' }
        ];
      });
      return rules;
    },
  },
  created() {
    this.getList();
  },
  mounted() {
    // 页面加载时确保至少有一个质检项
    if (this.form.customQualityCheck.length === 0) {
      this.form.customQualityCheck.push({ checkItem: '', checkContent: '' });
    }
  },
  methods: {
    /** 查询质检模板列表 */
    getList() {
      this.loading = true;
      listTemplate(this.queryParams).then(response => {
        this.templateList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        templateId: null,
        templateName: null,
        customQualityCheck: [{ checkItem: '', checkContent: '' }], // 重置时添加一项
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.templateId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加质检模板";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const templateId = row.templateId || this.ids;
      getTemplate(templateId).then(response => {
        const data = response.data;
        this.form.templateId = data.templateId;
        this.form.templateName = data.templateName;
        this.form.customQualityCheck = data.customQualityCheck || [];
        this.form.templateImagePaths = data.templateImagePaths || [];
        this.open = true;
        this.title = "修改质检模板";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            await this.$refs.imageUploadComponent.submitUpload();
            // 等待数据更新
            await this.$nextTick();
            if (!this.form.templateImagePaths) {
              this.$message.error('请上传至少一张图片');
              return;
            }
            // 提交表单逻辑
            if (this.form.templateId != null) {
              updateTemplate(this.form).then((response) => {
                this.$message.success('修改成功');
                this.open = false;
                this.getList();
              });
            } else {
              addTemplate(this.form).then((response) => {
                this.$message.success('新增成功');
                this.open = false;
                this.reset();
                this.getList();
              });
            }
          } catch (error) {
            this.$message.error('图片上传失败，请重试');
          }
        } else {
          this.$message.error('请填写完整的质检项和质检内容');
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const templateIds = row.templateId || this.ids;
      this.$modal.confirm('是否确认删除质检模板编号为"' + templateIds + '"的数据项？').then(function () {
        return delTemplate(templateIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('commodity/template/export', {
        ...this.queryParams
      }, `template_${new Date().getTime()}.xlsx`)
    },
    // 当添加或删除质检项时，无需手动更新验证规则，computed 会自动更新
    addQualityCheckItem() {
      if (this.form.customQualityCheck.length < 30) {
        this.form.customQualityCheck.push({ checkItem: '', checkContent: '' });
      } else {
        this.$message.warning("最多只能添加30项质检项");
      }
    },
    removeQualityCheckItem(index) {
      if (this.form.customQualityCheck.length === 1) {
        this.$message.warning("至少需要保留一个质检项");
      } else {
        this.form.customQualityCheck.splice(index, 1);
      }
    },
    /** 验证质检项数组 */
    validateQualityChecks(rule, value, callback) {
      if (!value || value.length === 0) {
        callback(new Error('至少需要一个质检项'));
      } else {
        callback();
      }
    },
  }
};
</script>
<style>
.hidden-column {
  display: none !important;
}

.upload-tip {
  margin-top: 10px;
  font-size: 14px;
  /* 提高字体大小 */
  color: #666;
  /* 字体颜色深一些，更容易阅读 */
  padding: 10px;
  background-color: #f5f7fa;
  /* 轻微的背景色 */
  border-left: 4px solid #409eff;
  /* 左边突出的边框颜色 */
  border-radius: 4px;
  /* 轻微的圆角 */
}

.image-container {
  display: flex;
  flex-wrap: nowrap;
  align-items: center;
  justify-content: center;
  /* 添加此行，使内容水平居中 */
}

.image-item {
  margin-right: 5px;
}
</style>